//
//  CountdownTimer.swift
//  GuessingRiddles
//
//  Created by 灵工邦 on 2024/5/22.
//

import Foundation

class CountdownTimer {
    private var timer: Timer?
    private var totalTime: TimeInterval
    private var timeRemaining: TimeInterval
    private var countdownHandler: ((TimeInterval) -> Void)?
    private var completion: (() -> Void)?

    init(totalTime: TimeInterval) {
        self.totalTime = totalTime
        self.timeRemaining = totalTime
    }

    func start(countdownHandler: @escaping (TimeInterval) -> Void, completion: @escaping () -> Void) {
        self.countdownHandler = countdownHandler
        self.completion = completion
        stop() // 确保在启动新计时器之前停止旧计时器
        timeRemaining = totalTime // 重置倒计时时间
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
        RunLoop.current.add(timer!, forMode: .common)
    }

    func stop() {
        timer?.invalidate()
        timer = nil
        print("Timer stopped")
    }

    @objc private func updateTime() {
        print("Updating time: \(timeRemaining)")
        guard timeRemaining > 0 else {
            stop()
            completion?()
            return
        }
        timeRemaining -= 1
        countdownHandler?(timeRemaining)
        if timeRemaining <= 0 {
            stop()
            completion?()
        }
    }
}
